<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

defined('IN_ADMIN') or die('Hacking Attempt!');

func::isLogin();
mysql::begin(1);

$sTable = 'tnf.order';

if(isset($_GET['id']) && is_numeric($_GET['id'])){
    $iId = $_GET['id'];
    //$aId = explode(',', $sId);//0: orderId, 1: customerId
    
    $sSql = 'SELECT customerId, total, content FROM '. $sTable .' WHERE orderId='. $iId;
    $aResult = mysql::querySql($sSql);
    $aRow = mysql::fetchSql($aResult);
    $iOrderTotal = $aRow['total'];
    $iCustomerId = $aRow['customerId'];
    $aVals = unserialize($aRow['content']);
    for($i=0; $i < (int)((count($aVals, 1)-3)/3); $i++){
        $iIdInvent = explode('.', $aVals['inventoryId'][$i]);
        $aInventory['inventoryId'][$i] = $iIdInvent[0];
    }

    $iIdDeleteOrder = mysql::deleteSql($sTable, 'orderId', $iId);

    //get debit amount
    $aRow = mysql::selectDebitAmount('debit', $iCustomerId);
    $iTotal = $aRow['amount'] - $iOrderTotal;
    $iIdUpdateDebit = mysql::updateSql('debit', array('amount' => $iTotal), 'customerid', $iCustomerId);

    //update inventory
    foreach($aInventory['inventoryId'] as $key=>$value){
       $aRow = mysql::selectInventoryQuantity('inventory', $value);
       $iInventoryQuantity = $aRow['quantity'] + $aVals['quantity'][$key];
       $iIdUpdateInventory = mysql::updateSql('inventory', array('quantity' => $iInventoryQuantity), 'inventoryId', $value);
   }
    
    if($iIdDeleteOrder && $iIdUpdateDebit && $iIdUpdateInventory){
        mysql::commit();
        func::redirect (func::makeUrl ('order', 'list'));
    }else
        mysql::rollBack();
}
?>
